package com.hsgene.common.util.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author wangbing
 * @version 1.0
 * @date 2019/1/14 18:31
 * Copyright: Copyright (c) 2019
 */
@Component
public class SpringApplicationContextUtil implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(SpringApplicationContextUtil.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringApplicationContextUtil.applicationContext == null) {
            SpringApplicationContextUtil.applicationContext = applicationContext;
        }
        logger.info("ApplicationContext配置成功,applicationContext对象：" + SpringApplicationContextUtil.applicationContext);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        Object obj = null;
        try {
            obj = getApplicationContext().getBean(name);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("没有找到对应的Bean:" + name);
        }

        return obj;
    }

    public static <T> T getBean(Class<T> clazz) {
        T obj = null;
        try {
            obj = getApplicationContext().getBean(clazz);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("没有找到对应的Bean:" + clazz.getName());
        }
        return obj;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        T obj = null;
        try {
            obj = getApplicationContext().getBean(name, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("没有找到对应的Bean:" + name + "::" + clazz.getName());
        }
        return obj;
    }
}
